<template>
  <div class="system-equipInfo-container">
    <el-card shadow="hover">
      <div class="system-equipInfo-search mb15">
        <el-form v-model="tableData.param" ref="queryRef" :inline="true" label-width="100px">
          <el-row>
            <el-col :span="6" class="colBlock">
              <el-form-item label="客户编号" prop="customerId">
                <el-input v-model="tableData.param.customerId" placeholder="请输入客户编号" clearable
                  @keyup.enter="equipInfoList" />
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colBlock">
              <el-form-item label="设备编号" prop="equipNum">
                <el-input v-model="tableData.param.equipNum" placeholder="请输入设备编号" clearable
                  @keyup.enter="equipInfoList" />
              </el-form-item>
            </el-col>

            <el-col :span="6" class="colBlock">
              <el-form-item label="设备激活状态" prop="equipActiveStatus">
                <el-select :style="{width:'150px'}" v-model="tableData.param.equipActiveStatus" placeholder="请选择设备激活状态" clearable>
                  <el-option v-for="dict in equip_active_status" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colBlock">
              <el-form-item label="设备名称" prop="equipName">
                <el-input v-model="tableData.param.equipName" placeholder="请输入设备名称" clearable
                  @keyup.enter="equipInfoList" />
              </el-form-item>
            </el-col>
            <el-col :span="8" class="colBlock">
              <el-form-item label="创建时间" prop="createdAt">
                <el-date-picker clearable style="width: 260px" type="daterange" v-model="tableData.param.createdAt"
                  range-separator="至" :disabledDate="disabledDate" value-format="YYYY-MM-DD" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="colBlock">
              <el-form-item>
                <el-button type="primary" @click="equipInfoList"><el-icon><ele-Search /></el-icon>搜索</el-button>
                <el-button @click="// @ts-ignore
                  resetQuery(queryRef)"><el-icon><ele-Refresh /></el-icon>重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" @click="handleAdd"
              v-auth="'api/v1/system/equipInfo/add'"><el-icon><ele-Plus /></el-icon>新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" :disabled="single" @click="// @ts-ignore
              handleUpdate(null)" v-auth="'api/v1/system/equipInfo/edit'"><el-icon><ele-Edit /></el-icon>修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" :disabled="multiple" @click="// @ts-ignore
              handleDelete(null)"
              v-auth="'api/v1/system/equipInfo/delete'"><el-icon><ele-Delete /></el-icon>删除</el-button>
          </el-col> -->
        </el-row>
      </div>
      <el-table v-loading="loading" :data="tableData.data" @selection-change="handleSelectionChange">
        <el-table-column label="客户编号" align="center" prop="customerId" min-width="150px" />
        <el-table-column label="设备编号" align="center" prop="equipNum" min-width="150px" />
        <el-table-column label="设备激活状态" align="center" prop="equipActiveStatus" :formatter="(row)=>statusFormat(equip_active_status,row.equipActiveStatus)"
          min-width="150px" />
        <el-table-column label="设备名称" align="center" prop="equipName" min-width="150px" />
        <el-table-column label="设备mac地址" align="center" prop="equipMac" min-width="150px" />
        <el-table-column label="设备IP地址" align="center" prop="equipIp" min-width="150px" />
        <el-table-column label="设备通信端口" align="center" prop="equipPort" min-width="150px" />
        <el-table-column label="协议类型" align="center" prop="protocolType" min-width="150px" :formatter="(row)=>statusFormat(equip_protocol_type,row.protocolType)"/>
        <el-table-column label="省份" align="center" :formatter="(row)=>getDistirectName(row.equipProvince)" prop="equipProvince" min-width="150px" />
        <el-table-column label="市" align="center" :formatter="(row)=>getDistirectName(row.equipCity)" prop="equipCity" min-width="150px" />
        <el-table-column label="区县" align="center" :formatter="(row)=>getDistirectName(row.equipCounty)" prop="equipCounty" min-width="150px" />
        <el-table-column label="描述信息" align="center" prop="equipDesc" min-width="150px" />
        <el-table-column label="创建时间" align="center" prop="createdAt" min-width="150px">
          <template #default="scope">
            <span>{{ proxy?.parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding" min-width="360px" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="
              handleUpdate(scope.row)"
              v-auth="'api/v1/equip/equipInfo/edit'"><el-icon><ele-EditPen /></el-icon>修改</el-button>
              <el-button type="primary" link @click="
              handleEquipRunData(scope.row)"
              v-auth="'/api/v1/equip/rundata/rtdata'"><el-icon><ele-Help /></el-icon>查看实时数据</el-button>
            <el-button type="primary" v-auth="'/api/v1/equip/rundata/sendMsg'" link @click="sendMsgClick(scope.row)"><el-icon><ele-Message /></el-icon>下发消息</el-button>
            <el-button type="primary" link @click="
              handleDelete(scope.row)"
              v-auth="'api/v1/equip/equipInfo/delete'"><el-icon><ele-DeleteFilled /></el-icon>删除</el-button>
              
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="tableData.total > 0" :total="tableData.total" v-model:page="tableData.param.pageNum"
        v-model:limit="tableData.param.pageSize" @pagination="equipInfoList" />
    </el-card>
    <ApiV1SystemEquipInfoEdit ref="editRef" @equipInfoList="equipInfoList"></ApiV1SystemEquipInfoEdit>
    <equipRunDataDialog ref="equipRunDataRef"></equipRunDataDialog>
    <sendMsg ref="sendMsgRef"></sendMsg>
  </div>
</template>
<script>
import { toRefs, reactive, onMounted, ref, defineComponent, computed, getCurrentInstance, toRaw } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getDistirectName } from '/@/components/CitySelector/utils'
import {
  listEquipInfo,
  getEquipInfo,
  delEquipInfo,
  addEquipInfo,
  updateEquipInfo,
} from "../../api/equip";

import ApiV1SystemEquipInfoEdit from "./edit.vue"
import equipRunDataDialog from "./equipRunDataDialog.vue"
import sendMsg from './sendMsg.vue'
import lodash from 'lodash'
export default defineComponent({
  name: "ApiV1SystemEquipInfoList",
  components: {
    ApiV1SystemEquipInfoEdit,
    equipRunDataDialog,
    sendMsg
  },
  setup() {
    const { proxy } = getCurrentInstance()
    const loading = ref(false)
    const queryRef = ref()
    const editRef = ref();
    const equipRunDataRef = ref();
    const sendMsgRef = ref();
    // 是否显示所有搜索选项
    const showAll = ref(false)
    // 非单个禁用
    const single = ref(true)
    // 非多个禁用
    const multiple = ref(true)
    // 字典选项数据        
    const {
      equip_active_status,
      equip_protocol_type
    } = proxy.useDict('equip_active_status','equip_protocol_type')

    // 标签字典翻译
    const statusFormat = (dictData,status) => {
      return proxy.selectDictLabel(dictData, status);
    }

    const state = reactive({
      ids: [],
      tableData: {
        data: [],
        total: 0,
        loading: false,
        param: {
          pageNum: 1,
          pageSize: 10,
          id: undefined,
          equipNum: undefined,
          equipType: undefined,
          equipActiveStatus: undefined,
          equipName: undefined,
          equipMac: undefined,
          equipIp: undefined,
          equipPort: undefined,
          protocolType: undefined,
          encryptKey: undefined,
          customerId: undefined,
          equipProvince: undefined,
          equipCity: undefined,
          equipCounty: undefined,
          equipCoordinate: undefined,
          equipPosition: undefined,
          equipDesc: undefined,
          tenantId: undefined,
          tenantName: undefined,
          createdBy: undefined,
          createdAt: undefined,
          dateRange: []
        },
      },
    });
    // 页面加载时
    onMounted(() => {
      initTableData();
    });
    // 初始化表格数据
    const initTableData = () => {
      equipInfoList()
    };
    /** 重置按钮操作 */
    const resetQuery = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
      equipInfoList()
    };
    // 获取列表数据
    const equipInfoList = () => {
      loading.value = true
      const params = state.tableData.param
      if(params.createdAt && params.createdAt.length==2) {
        params.created_start_time = params.createdAt[0]
        params.created_end_time = params.createdAt[1]
      } else {
        if(params.created_start_time) 
          delete params.created_start_time
        if(params.created_end_time)
          delete params.created_end_time
      }
      if(params.createdAt) {
          delete params.createdAt
        }
      listEquipInfo(state.tableData.param).then((res) => {
        let list = res.data.list ?? [];
        list.map((item) => {
          item.createdBy = item.createdUser?.userNickname
        })
        state.tableData.data = list;
        state.tableData.total = res.data.total;
        loading.value = false
      })
    };
    const toggleSearch = () => {
      showAll.value = !showAll.value;
    }
    // 多选框选中数据
    const handleSelectionChange = (selection) => {
      state.ids = selection.map(item => item.id)
      single.value = selection.length != 1
      multiple.value = !selection.length
    }
    const handleAdd = () => {
      editRef.value.openDialog()
    }

    const handleEquipRunData = (row) => {
      equipRunDataRef.value.openDialog(toRaw(row));
    }

    const handleUpdate = (row) => {
      if (!row) {
        row = state.tableData.data.find((item) => {
          return item.id === state.ids[0]
        })
      }
      editRef.value.openDialog(toRaw(row));
    };
    const handleDelete = (row) => {
      let msg = '你确定要删除所选数据？';
      let id = [];
      if (row) {
        msg = `此操作将永久删除数据，是否继续?`
        id = [row.id]
      } else {
        id = state.ids
      }
      if (id.length === 0) {
        ElMessage.error('请选择要删除的数据。');
        return
      }
      ElMessageBox.confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
          const customer_id = lodash.get(row,'customerId')
          const equip_num = lodash.get(row,'equipNum')
          delEquipInfo({customer_id,equip_num}).then(() => {
            ElMessage.success('删除成功');
            equipInfoList();
          })
        })
        .catch(() => { });
    }

    const sendMsgClick = (row)=>{
      console.log(row);
      console.log("sendMsgRef.value",sendMsgRef.value);
      sendMsgRef.value.openDialog(row)
    }

    const disabledDate =(time)=>{  
      // 获取当前日期  
      const currentDate = new Date();  
      // 设置时间部分为 00:00:00，以确保比较的是日期部分  
      currentDate.setHours(0, 0, 0, 0);  
      // 如果传入的日期大于当前日期，则禁用  
      return time.getTime() > currentDate.getTime();  
    } 
    return {
      sendMsgRef,
      sendMsgClick,
      disabledDate,
      getDistirectName,
      equip_active_status,
      equip_protocol_type,
      statusFormat,
      proxy,
      editRef,
      equipRunDataRef,
      showAll,
      loading,
      single,
      multiple,
      queryRef,
      resetQuery,
      equipInfoList,
      toggleSearch,
      handleSelectionChange,
      handleAdd,
      handleUpdate,
      handleDelete,
      handleEquipRunData,
      ...toRefs(state),
    }
  }
})
</script>
<style lang="scss" scoped>
.colBlock {
  display: block;
}

.colNone {
  display: none;
}

.ml-2 {
  margin: 3px;
}
</style>